﻿@using System.Web.Optimization
@using VocaDb.Model.Helpers
@using VocaDb.Model.Utils
@using VocaDb.Web.Helpers;
@using R = ViewRes.Album;
@using Res = ViewRes.Album.EditStrings;
@using EditRes = ViewRes.EntryEditStrings;
@using ValidationErrors = VocaDb.Model.Resources.AlbumValidationErrors;
@inherits VocaDb.Web.Code.VocaDbPage<VocaDb.Web.Models.Album.AlbumEditViewModel>

@{
	PageProperties.Title = string.Format(R.EditStrings.EditTitle, Model.Name);
	ViewBag.Parents = new[] { 
		Html.ActionLink(ViewRes.SharedStrings.Albums, "Index"), 
		Html.ActionLink(Model.Name, "Details", new { id = Model.Id }) 
	};

	var validationErrors = new Dictionary<string, string> {
		{ "validationError_duplicateArtist", ValidationErrors.DuplicateArtist },
		{ "validationError_unspecifiedNames", ValidationErrors.UnspecifiedNames },
		{ "validationError_needArtist", ValidationErrors.NeedArtist },
		{ "validationError_needCover", ValidationErrors.NeedCover },
		{ "validationError_needReferences", ValidationErrors.NeedReferences },
		{ "validationError_needReleaseYear", ValidationErrors.NeedReleaseYear },
		{ "validationError_needTracks", ValidationErrors.NeedTracks },
		{ "validationError_needType", ValidationErrors.NeedType },
	};
	
}

@section Toolbar {
@if (Model.CanDelete) {
	if (!Model.Album.Deleted) {
		<a href="#" id="deleteLink" data-bind="click: function() { deleteViewModel.dialogVisible(true); }">@ViewRes.SharedStrings.Delete</a>
	} else if (Login.CanDeleteEntries) {
		@Html.ActionLink(ViewRes.EntryEditStrings.Restore, "Restore", new { id = Model.Id }, new { id = "restoreLink" })
        if (Login.CanMoveToTrash) {
			@Html.Raw("&nbsp;")
			@Html.ActionLink(R.EditStrings.MoveToTrash, "MoveToTrash", new { id = Model.Id }, new { id = "trashLink", onclick = string.Format("return confirm(\"{0}\");", R.EditStrings.ConfirmMoveToTrash) })
		}
	}
}
@if (Login.CanMergeEntries) {
	@Html.Raw("&nbsp;")	
	@Html.ActionLink(ViewRes.EntryEditStrings.Merge, "Merge", new { id = Model.Id }, new { id = "mergeLink" })
}
}

@section BodyScripts {
<script type="text/javascript">
    $(document).ready(function() { 

        vdb.resources.albumEdit = {
        	addExtraArtist: "@Html.Raw(AjaxRes.SharedStrings.AddExtraArtist)",
			addNewSong: "@Html.Raw(AjaxRes.AlbumStrings.AddNewSong)",
        	addToTracks: '@Html.Raw(AjaxRes.AlbumStrings.AddToTracks)',
            removeFromTracks: '@Html.Raw(AjaxRes.AlbumStrings.RemoveFromTracks)'
        };

        $("#tabs").tabs();

	});
</script>

@Scripts.Render("~/bundles/shared/edit", "~/bundles/Album/Edit")

<script type="text/javascript">
	$(function() {

		moment.locale('@Culture');
		ko.punches.enableAll();

		vdb.resources.entryEdit = {
			saveWarning: @ToJS(EditRes.SaveWarning)
		};

		var canBulkDeletePVs = @ToJS(Login.Manager.HasPermission(VocaDb.Model.Domain.Security.PermissionToken.BulkDeletePVs));
		var rootPath = '@RootPath';
		var urlMapper = new vdb.UrlMapper(rootPath);

		var repoFactory = new vdb.repositories.RepositoryFactory(urlMapper, @LanguagePreferenceInt);
		var repo = repoFactory.albumRepository();
		var songRepo = repoFactory.songRepository();
		var artistRepo = repoFactory.artistRepository();
		var pvRepo = repoFactory.pvRepository();
		var userRepo = repoFactory.userRepository();
		var eventRepo = repoFactory.eventRepository();
		var webLinkCategoryJson = @Html.Raw(JsonHelpers.Serialize(Translate.WebLinkCategoryNames.AllFields));
		var artistRoleJson = @Html.Raw(JsonHelpers.Serialize(Translate.ArtistRoleNames.GetValuesAndNames(AppConfig.ArtistRoles), false));
		var allowCustomTracks = @ToJS(VocaDb.Model.Utils.AppConfig.AllowCustomTracks);
		var editedModel = @Html.Raw(JsonHelpers.Serialize(Model.EditedAlbum));
		var viewModel;

		if (editedModel) {

			viewModel = new vdb.viewModels.AlbumEditViewModel(repo, songRepo, artistRepo, pvRepo, userRepo, eventRepo, urlMapper,
				artistRoleJson, webLinkCategoryJson, editedModel, allowCustomTracks, canBulkDeletePVs, new vdb.ui_dialog.DialogService());

			ko.applyBindings(viewModel);

		} else {

			repo.getForEdit(@Model.Id, function (model) {

				viewModel = new vdb.viewModels.AlbumEditViewModel(repo, songRepo, artistRepo, pvRepo, userRepo, eventRepo, urlMapper,
					artistRoleJson, webLinkCategoryJson, model, allowCustomTracks, canBulkDeletePVs, new vdb.ui_dialog.DialogService());

				ko.applyBindings(viewModel);

			});

		}

		initPage();

	});
</script>
}


@Helpers.ValidationSymmaryDiv(R.EditStrings.UnableToSaveProperties)

@KnockoutHelpers.EntryValidationMessage(Model.Draft, validationErrors, "glalbums")

<br />
<form action="@Url.Action("Edit", "Album")" method="POST" enctype="multipart/form-data" data-bind="submit: submit, visible: true" style="display: none;">

	@Helpers.SaveAndBackBtn(Url.Action("Details", new { Model.Id }))
	
	<div id="tabs">

		<ul>
			<li><a href="#basicInfoTab">@EditRes.BasicInfo</a></li>
			<li><a href="#artistsTab">@R.EditStrings.ArtistsTab</a></li>
			<li><a href="#discsTab">@Res.DiscsTab</a></li>
			<li><a href="#tracksTab">@R.EditStrings.TracksTab</a></li>
			<li><a href="#picsTab">@R.EditStrings.PicturesTab</a></li>
			<li><a href="#pvsTab">@R.EditStrings.MediaTab</a></li>
		</ul>

		<div id="basicInfoTab">

			<div class="editor-label">
				<label>@EditRes.DefaultLanguageSelection</label>
			</div>
			<div class="editor-field">
				@KnockoutHelpers.LanguageSelectionDropDown("defaultNameLanguage")
			</div>

			<div class="editor-label">
				@Helpers.HelpLabel(R.EditStrings.BaNames, ViewRes.EntryEditStrings.NameHelp)
				@Helpers.RequiredField()
				<span data-bind="visible: validationError_unspecifiedNames, qTip" class="icon errorIcon" title="@ValidationErrors.UnspecifiedNames"></span>
			</div>
			<div class="editor-field" data-bind="with: names">
				@{ Html.RenderPartial("KnockoutPartials/_NamesEditor", new VocaDb.Web.Models.Shared.NamesEditorViewModel()); }
			</div>

			<div class="editor-label">
				<label>@R.EditStrings.BaMainCoverPicture</label>
			</div>
			<div class="editor-field">
				<table>
					<tr><td>
						<img src="@Url.Action("CoverPictureThumb", new { id = Model.Id })" alt="@R.EditStrings.ImagePreview" class="coverPic" />
					</td><td>
						<p>@string.Format(R.EditStrings.BaPictureInfo, string.Join(", ", ImageHelper.AllowedExtensions), ImageHelper.MaxImageSizeMB)</p>
						<input type="file" id="coverPicUpload" name="coverPicUpload" />
					</td></tr>
				</table>
			</div>

			<div class="editor-label">
				<label>@Res.BaDescription</label>
				@Helpers.MarkdownNotice()
			</div>
			<div class="editor-field entry-edit-description" data-bind="with: description">
				@{ Html.RenderPartial("Partials/_EnglishTranslatedStringEdit"); }
			</div>

			<div class="editor-label">
				@Helpers.HelpLabel(R.EditStrings.BaDiscType, Model.DiscTypeDescriptions)
			</div>
			<div class="editor-field">
				<div class="row-fluid">
					@KnockoutHelpers.DropdownList(Model.AllDiscTypes, "discTypeStr")
					<span data-bind="visible: validationError_needType, qTip" class="icon errorIcon" title="@ValidationErrors.NeedType"></span>
				</div>
			</div>
			
			<div class="editor-label">
				<label>@Res.BaReleaseEvent</label>
			</div>
			<div class="editor-field">
				@KnockoutHelpers.BasicEntryLinkLockingAutoComplete("releaseEventAutoComplete", "releaseEvent", "createNewItem: 'Create new event \\\'{0}\\\''")
			</div>

			<table><tr>
				<td>@R.EditStrings.BaReleaseDate</td>
				<td>
					<div class="editor-label">
						<label>
							@R.EditStrings.BaReleaseYear
						</label>
					</div>
					<div class="editor-field">
						<input type="number" data-bind="textInput: releaseYear" class="input-small" size="10" maxlength="4" min="39" max="3939" />
						<span data-bind="visible: validationError_needReleaseYear, qTip" class="icon errorIcon" title="@ValidationErrors.NeedReleaseYear"></span>
					</div>				
				</td>
				<td>
					<div class="editor-label">
						<label>@Res.BaReleaseMonth</label>
					</div>
					<div class="editor-field">
						<input type="number" data-bind="textInput: releaseMonth" class="input-mini" size="4" maxlength="2" min="1" max="12" />
					</div>				
				</td>
				<td>
					<div class="editor-label">
						<label>@Res.BaReleaseDay</label>
					</div>
					<div class="editor-field">
						<input type="number" data-bind="textInput: releaseDay" class="input-mini" size="4" maxlength="2" min="1" max="31" />
					</div>				
				</td>
			</tr></table>
			
			<button class="btn" data-bind="visible: !releaseDate() && eventDate(), click: function() { releaseDate(eventDate()); }">
				Use event date <span data-bind="text: eventDate() ? eventDate().format('L') : null"></span>
			</button>

			<div class="editor-label">
				@Helpers.HelpLabel(R.EditStrings.BaCatNum, "Usually catalog numbers are in the format ABC-1234, please do not add extra whitespace.")
			</div>
			<div class="editor-field">
				<input type="text" data-bind="textInput: catalogNumber" />
			</div>
			
			<div class="editor-label">
				@Helpers.HelpLabel(Res.BaBarcode, "Barcodes are usually plain numbers, for example 01234567. They can be scanned from the product package.<br /><br /><img src='" + Url.Content("~/Content/barcode.png" + "' />"))
			</div>
			<div class="editor-field">
				<div data-bind="foreach: identifiers">
					<div>
						<span data-bind="text: $data" style="width: 150px; display: inline-block;"></span>
						<a href="#" class="textLink deleteLink" data-bind="click: function() { $parent.identifiers.remove($data); }">@ViewRes.SharedStrings.Delete</a>
					</div>
				</div>
				<input type="text" placeholder="New barcode" maxlength="30" data-bind="textInput: newIdentifier, focusout: function() { createNewIdentifier(); } " />
			</div>
			
			<div class="editor-label">
				@Helpers.HelpLabel(EditRes.WebLinks, ViewRes.EntryEditStrings.ExternalLinksQuickHelp)
			</div>
			<div class="editor-field" data-bind="with: webLinks">
				@KnockoutHelpers.WebLinksEditViewKnockout(true)
			</div>

			<div class="editor-label">
				@Helpers.HelpLabel(EditRes.Status, Resources.CommonMessages.EntryStatusExplanation)
			</div>
			<div class="editor-field">
				@KnockoutHelpers.DropdownList(Translate.EntryStatusNames.GetValuesAndNamesStrings(Model.AllowedEntryStatuses), "status")
			</div>

		</div>
		
		<div id="discsTab" data-bind="with: discs">
			
			<div class="alert alert-info">
				@Res.DiNote
			</div>

			<table>
				<thead>
					<tr>
						<th></th>
						<th>@Res.DiName</th>
						<th>@Res.DiType</th>
						<th></th>
					</tr>
				</thead>
				<tbody data-bind="foreach: items">
					<tr>
						<td>
							<span data-bind="text: $index() + 1"></span>
						</td>
						<td>
							<input type="text" data-bind="textInput: name" placeholder="Name" maxlength="50" />
						</td>
						<td>
							<select data-bind="value: mediaType" class="input-small">
								<option value="Audio">@Res.DiAudio</option>
								<option value="Video">@Res.DiVideo</option>
							</select>
						</td>
						<td>
							<a data-bind="click: $parent.remove" href="#" class="iconLink removeLink">@ViewRes.SharedStrings.Remove</a>							
						</td>
					</tr>
				</tbody>
			</table>
			
			<a href="#" class="textLink addLink" data-bind="click: add">@Res.DiAddRow</a>

		</div>

		<div id="tracksTab">
			
			<div class="alert" data-bind="visible: validationError_needTracks">
				<span>@ValidationErrors.NeedTracks</span>
			</div>
			
			<!-- ko if: tracks().length-->
			<p>@R.EditStrings.TrTrackNameHelp</p>

			<table>
				<thead>
					<tr>
						<th></th>
						<th><input type="checkbox" data-bind="checked: allTracksSelected" /></th>
						<th>@R.EditStrings.TrDiscHead</th>
						<th>@R.EditStrings.TrTrackHead</th>
						<th>@R.EditStrings.TrNameHead</th>
						<th colspan="3" />
					</tr>
				</thead>
				<tbody data-bind="sortable: tracks">
					@{ Html.RenderPartial("Partials/_SongInAlbumEdit"); }
				</tbody>
			</table>

			<br />
			<a data-bind="click: editMultipleTrackProperties" href="#" class="textLink editLink">@R.EditStrings.TrSetArtists</a>
			<br /><br />
			<!-- /ko -->

			<h4>@R.EditStrings.AddNew</h4>
			<input type="text" data-bind="songAutoComplete: trackSearchParams" maxlength="128" placeholder="@ViewRes.SharedStrings.Search" class="input-xlarge" />
			<p>@R.EditStrings.TrAddTrackHelp</p>
		</div>

		<div id="artistsTab">
			
			<div class="alert" data-bind="visible: validationError_needArtist">
				<span>@ValidationErrors.NeedArtist</span>
			</div>

			<table data-bind="visible: artistLinks().length">
				<thead>
					<tr>
						<th>Artist</th>
						<th>Support</th>
						<th>Roles</th>
						<th>Actions</th>
					</tr>
				</thead>
				<tbody data-bind="foreach: artistLinks">
					@{ Html.RenderPartial("Partials/_ArtistForAlbumEdit"); }
				</tbody>
			</table>

			<br />
			<h4>@R.EditStrings.ArAddArtist</h4>
			<input type="text" data-bind="artistAutoComplete: artistSearchParams" maxlength="128" placeholder="@ViewRes.SharedStrings.Search" class="input-xlarge" />

		</div>
		
		<div id="picsTab" data-bind="with: pictures">
			
			<p>@R.EditStrings.PiPicturesGuide</p>
			<p>@string.Format(R.EditStrings.BaPictureInfo, string.Join(", ", ImageHelper.AllowedExtensions), ImageHelper.MaxImageSizeMB)</p>

			<table>
				<tbody data-bind="foreach: pictures">
					@{ Html.RenderPartial("KnockoutPartials/_EntryPictureFileEdit"); }
				</tbody>
			</table>
			
			<a data-bind="click: add" href="#" class="addLink textLink">@R.EditStrings.PiCreateNew</a>

		</div>

		<div id="pvsTab" data-bind="with: pvs">

			<p>@R.EditStrings.PvIntro</p>

			<table data-bind="visible: pvs().length">
				<thead>
					<tr>
						<th>@R.EditStrings.PvService</th>
						<th>@R.EditStrings.PvType</th>
						<th colspan="2">@R.EditStrings.PvName</th>
						<th>Date</th>
						<th>@R.EditStrings.PvAuthor</th>
						<th></th>
					</tr>
				</thead>
				<tbody data-bind="foreach: pvs">
					@{ Html.RenderPartial("PVs/_PVEdit"); }
				</tbody>
			</table>

			<br />
			<h4>@R.EditStrings.PvAdd</h4>
			<p>@R.EditStrings.PvSupportedServices</p>
			<p>
				@R.EditStrings.PvURL
				<input type="text" data-bind="textInput: newPvUrl" maxlength="255" size="40" class="input-xlarge" />
			</p>

			<a data-bind="click: add" href="#" class="textLink addLink">@ViewRes.SharedStrings.Add</a>
			@Helpers.AjaxLoader("pvLoader")

		</div>

	</div>
	<br />
	
	<p>@ViewRes.EntryEditStrings.UpdateNotes</p>
	<textarea data-bind="value: updateNotes" class="input-xxlarge" rows="4" maxlength="200"></textarea>
	
	<br />
	@Helpers.SaveAndBackBtn(Url.Action("Details", new { Model.Id }))
	
	<!-- JSON model to be posted to the server -->
	@Html.HiddenForKnockout(m => m.EditedAlbum, "value: submittedJson")

</form>

<div data-bind="with: artistRolesEditViewModel">
	@{ Html.RenderPartial("Partials/_ArtistRolesEditViewModel"); }
</div>	

<div data-bind="with: editedArtistLink">
	@{ Html.RenderPartial("Partials/_CustomNameEdit"); }
</div>

<div data-bind="dialog: {autoOpen: false, modal: true, width: 550 }, dialogButtons: trackPropertiesDialogButtons, dialogVisible: trackPropertiesDialogVisible" style="display:none;" title="@R.EditStrings.TrackPropertiesTitle">

	@{ Html.RenderPartial("Partials/_TrackProperties"); }

</div>

@EntryDetailsHelpers.EntryDeletePopup(ViewRes.EntryEditStrings.ConfirmDelete)
